package com.kui.aop;

import com.kui.annotation.AuthCheck;
import com.kui.enums.UserEnums;
import com.kui.exception.ErrorCode;
import com.kui.exception.ThrowUtils;
import com.kui.model.entity.User;
import com.kui.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 权限校验
 */
@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;

    /**
     * 切面
     *
     * @param joinPoint
     * @param authCheck
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //拿到必须得mustRole
        String mustRole = authCheck.mustRole();
        //通过RequestContextHolder 全局获取 request对象
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        // 转换为ServletRequestAttributes
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User loginUser = userService.getLoginUser(request);
        // 通过mustRole判断是否需要校验
        UserEnums mustUserRole = UserEnums.getUserByValue(mustRole);
        //如果必须需要的角色为空，就证明不需要特殊角色，就直接放行
        if (mustUserRole == null) {
            return joinPoint.proceed();
        }
        //拿到当前用户的角色
        UserEnums currentUserRole = UserEnums.getUserByValue(loginUser.getUserRole());
        System.out.println("当前用户角色为：" + currentUserRole);
        if (currentUserRole == null) {
            ThrowUtils.throwIf(true, ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        //如果这个操作需要管理员权限，但是当前用户不是管理员，就抛出异常
        //这里要出要对比的是枚举值
        if (UserEnums.ADMIN.equals(mustUserRole) && !UserEnums.ADMIN.equals(currentUserRole)) {
            ThrowUtils.throwIf(true, ErrorCode.NO_AUTH_ERROR, "权限等级不够");
        }
        //放行
        return joinPoint.proceed();
    }
}
